import base64
import json
import math
import random
from urllib.parse import urlencode
from HTTP.HttpUtil import HttpUtil
from Res import Resources


class ErolabUtil:
    def __init__(self,gameid,proxy_info=None):
        self.game_id = gameid
        # 滑动验证码参数
        self.canvas_width = 210
        self.slider_l = 42
        self.slider_r = 9
        self.base_speed = 0.8
        self.max_speed = 4.5
        self.accel = 0.15
        self.decel_start_ratio = 0.72
        self.http = HttpUtil()
        self.proxy =proxy_info
        self.user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        #
    def generate_gap(self):
        """生成缺口位置"""
        s = self.slider_l + 2 * self.slider_r + 3
        return (
            random.randint(s + 10, self.canvas_width - (s + 10)),
            random.randint(10 + 2 * self.slider_r, 135 - (s + 10))
        )

    def _calculate_y_offset(self, current_x, velocity):
        """计算Y轴偏移"""
        return round(
            math.sin(current_x / 17.5) * 3 +
            math.cos(current_x / 6.2) * 1.3 +
            random.gauss(0, 1.5) * (velocity / self.max_speed)
        )

    def generate_trajectory(self, target_x):
        """生成动态长度轨迹"""
        trajectory = []
        current_x = 0.0
        velocity = self.base_speed
        decel_start = target_x * self.decel_start_ratio

        # 生成初始操作抖动
        for _ in range(random.randint(8, 15)):
            trajectory.append(random.randint(-2, 2))
            current_x += velocity * (0.15 + random.random() * 0.3)

        # 主滑动阶段
        while current_x < target_x:
            if current_x < decel_start:
                velocity += self.accel * (0.8 + random.random() * 0.4)
                velocity = min(velocity, self.max_speed)
            else:
                velocity -= self.accel * (2.2 + random.random() * 1.0)
                velocity = max(velocity, self.base_speed * 0.8)

            # 增加随机抖动频率
            if random.random() < 0.3:
                trajectory.append(random.randint(-2, 2))
                current_x += velocity * (0.8 + random.random() * 0.4)
            
            y = self._calculate_y_offset(current_x, velocity)
            trajectory.append(y)
            current_x += velocity * (0.7 + random.random() * 0.5)

        # 添加最终稳定操作
        trajectory += [trajectory[-1] + random.randint(-2, 2) for _ in range(random.randint(8, 20))]
        
        # 添加随机停顿
        for _ in range(random.randint(0, 3)):
            trajectory.append(trajectory[-1])
            
        return trajectory

    def get_hash(self):
        hash = None
        gap_x, gap_y = self.generate_gap()
        # 生成轨迹（假设需要移动150像素）
        target_x = gap_x - 35  # 根据实际布局调整
        trajectory = self.generate_trajectory(target_x)
        result = self.verify_captcha(trajectory)
        if result["status"] == "SUCCESS":
            hash = result["data"]["hashCode"]
        return hash
    def format_post_data(self, trajectory):
        """格式化轨迹数据为POST参数"""
        return urlencode({'datas[]': trajectory}, doseq=True)

    def verify_captcha(self,trajectory):
        """执行验证请求"""
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Referer': 'https://sadpki-portal.ebuajk.com/login/',
            'User-Agent': self.user_agent
        }

        try:
            result,http_code,erro = self.http.post(
                url='https://sadpki-portal.ebuajk.com/api/v2/captcha/isVerify',
                data=self.format_post_data(trajectory),
                headers=headers,
                proxy=self.proxy
            )
            return json.loads(result)
        except Exception as e:
            return {'status': 'error', 'message': str(e)}

    def GuestLogin(self,hash):
        """执行验证请求"""
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Referer': 'https://sadpki-portal.ebuajk.com/login/',
            'User-Agent': self.user_agent
        }

        try:
            result,http_code,erro = self.http.post(
                url='https://sadpki-portal.ebuajk.com/api/v2/guestLogin',
                data=f"gameId={self.game_id}&hashCode={hash}",
                headers=headers,
                proxy=self.proxy
            )
            return json.loads(result)
        except Exception as e:
            return {'status': 'error', 'message': str(e)}
    def SignUp(self, user,password,hash):
        """执行验证请求"""
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Referer': 'https://sadpki-portal.ebuajk.com/login/',
            'User-Agent': self.user_agent
        }

        try:
            data={}
            data["account"]=user
            data["password"] = base64.b64encode(password.encode('utf-8')).decode('utf-8')
            data["game_id"] = ''
            data["jwt"] = ''
            data["hashCode"] = hash
            result,http_code,erro = self.http.post(
                url='https://sadpki-portal.ebuajk.com/api/v2/signup',
                data=urlencode(data),
                headers=headers,
                proxy=self.proxy
            )
            return json.loads(result)
        except Exception as e:
            return {'status': 'error', 'message': str(e)}
    def Login(self, user,password,hash):
        """执行验证请求"""
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Referer': 'https://sadpki-portal.ebuajk.com/login/',
            'User-Agent': self.user_agent
        }

        try:
            data={}
            data["account"]=user
            data["password"] = base64.b64encode(password.encode('utf-8')).decode('utf-8')
            data["game_id"] = self.game_id
            data["hashCode"] = hash
            result,http_code,erro = self.http.post(url='https://sadpki-portal.ebuajk.com/api/v2/login',data=urlencode(data),headers=headers,proxy=self.proxy)
            return json.loads(result)
        except Exception as e:
            return {'status': 'error', 'message': str(e)}

